import { defineStore } from 'pinia';
import request from '/@/utils/request';
import * as SignalR from '@microsoft/signalr';
import {getToken} from "/@/utils/request.ts";
import {useUserInfo} from "./userInfo.ts";
import dayjs from "dayjs";
import {formatMessage} from "/@/utils/Tools.js";

// signalr链接实例
var connection = null;

export const useChatStore = defineStore('chatStore', {
	state: () => ({
		// 聊天列表
		online: [],
		offline: [],

		// 当前聊天id
		chatId: '',

		// 当前聊天信息
		chatMessage: [],

	}),
	actions: {
		// 上线
		beOnline() {
			if(connection) {
				return;
			}
			// 初始化SignalR对象
			connection = new SignalR.HubConnectionBuilder()
				.configureLogging(SignalR.LogLevel.Information)
				.withUrl(`/api/hubs/onlineUser?access_token=${getToken()}`)
				.withAutomaticReconnect({
					nextRetryDelayInMilliseconds: () => {
						return 5000; // 每5秒重连一次
					},
				})
				.build();

			// 启动连接
			connection.start().then(() => {
				console.log('启动连接');
			});

			// 接收聊天
			connection.on('ReceiveMessage', (data) => {
				let req = JSON.parse(data.message);
				let index = this.offline.findIndex(item => item.id == req.UserId);
				if(index != -1) {
					this.online.push(this.offline[index]);
					this.offline.splice(index, 1);
				} else {
					if(!this.online.find(item => item.id == req.UserId)) {
						this.online.push({
							id: req.UserId,
							name: req.UserName
						})
						if(!this.chatId) {
							this.chatId = req.UserId;
						}
					}
				}

				let obj = {
					type: 2, // 1我，2客户
					name: req.UserName,
					msg: formatMessage(req.Message),
					time: dayjs(req.CreateTime).format('YYYY-MM-DD HH:mm:ss')
				}
				if(req.UserId == this.chatId) {
					this.chatMessage.push(obj);
				}
			})

			// 客户离线
			connection.on('OnlineUserDisconnected', (data) => {
				console.log(data);
			})

		},

		// 下线
		beOutline() {
			// 断开连接
			connection.onclose(async () => {
				console.log('断开连接');
			});
		},

		// 获取所有聊天人列表
		async getChatList() {
			let res = await request({
				url: `/api/chat/sys/allChatClientInfo`,
				method: 'get',
			})
			let data = res.data.result;
			this.online = data.onlineClients;
			this.offline = data.offlineClients;
		},

		// 获取当前的聊天消息列表
		async getChatMessage(id) {
			let oChat = null;
			if(!id) {
				if(!this.online.length) {
					return;
				}
				oChat = this.online[0];
			} else {
				oChat = this.online.find(item => item.id == id);
				if(!oChat) {
					oChat = this.offline.find(item => item.id == id);
				}
			}
			
			// 清空消息
			this.chatMessage = [];
			this.chatId = oChat.id;
			
			let res = await request({
				url: `/api/chat/sys/clientMessage/${oChat.id}`,
				method: 'get',
			})
			let userId = useUserInfo().userInfos.userId;
			console.log(userId);
			let data = res.data.result;
			let list = [];
			data.forEach(item => {
				if(item.message) {
					list.push({
						type: item.sourceUserId == userId ? 1 : 2, // 1我，2客户
						name: item.sourceUserName,
						msg: formatMessage(item.message),
						time: item.createTime
					})
				}
			})
			// 设置消息
			this.chatMessage = list;
		},

		// 发送消息
		async sendChatMessage(params) {
			let res = await request({
				url: '/api/chat/sys/customerServiceSendMessage',
				method: 'post',
				data: params
			})
		},
		
	},
});
